import $store from '@/store/index.js'
export default {
	//全局配置
	common: {
		baseUrl:'http://chejian.yuelaiwangluo.com/api/',
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			'Content-Type': 'application/x-www-form-urlencoded',
			'Content-Type': 'application/json',
		},
		data: {},
		method: 'GET',
		dataType: 'json'
	},
	//请求 返回peomise
	request(options = {}) {
		options.url = this.common.baseUrl + options.url;
		options.header = options.header || this.common.header;
		options.header.token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
		options.data = options.data || this.common.data;
		options.method = options.method || this.common.method;
		options.dataType = options.dataType || this.common.dataType;
		// 请求
		return new Promise((res, rej) => {
			// 请求之前
			uni.request({
				...options,
				success: (result) => {
					// 服务端请求失败
					if(result.statusCode !==200 ){
						if(result.data.code == 401){
							uni.showToast({
								title:result.data.msg,
								icon:'none'
							});
							setTimeout(()=>{
								uni.switchTab({
									url: '/pages/pagesA/my/index'
								})
							},2000)
						}
						if(options.toast !== false){
							setTimeout(()=>{
								uni.showToast({
									title:result.data.msg || '服务端未请求',
									icon:'none'
								});
							},1000)
							return rej(result)
						};
					}
					 res(result)
				},
				fail: (error) => {
					return uni.showToast({
						title:error.errMsg+'11' || '请求失败',
						icon:'none'
					})
					return rej()
				}
			})
		})

	},
	
	//get请求
	get(url,data={} ,options = {}){
		options.url = url,
		options.data = data,
		options.method = 'GET'
		return this.request(options)
	},
	//post请求
	post(url,data={} ,options = {}){
		options.url = url,
		options.data = data,
		options.method = 'POST'
		return this.request(options)
	},
	//delate请求
	del(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
	//put请求
	put(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
}
